package gops

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"
)

// 反斜线中的 json:"url"、json:"headers" 和 json:"data" 是 JSON 标签（tag），
// 它们指定了在 JSON 编码和解码过程中使用的字段名称。

type RequestGetOptions struct {
	URL     string            `json:"url"`
	Params  map[string]string `json:"params"`
	Headers map[string]string `json:"headers"`
}

// RequestPostOptions 结构体用于封装POST请求的选项
type RequestPostOptions struct {
	URL     string            `json:"url"`
	Data    map[string]any    `json:"data"`
	Headers map[string]string `json:"headers"`
}

type RequestCustomeResponse struct {
	Code    int    `json:"code"`
	Msg     string `json:"msg"`
	Content any    `json:"content"`
}

func RequestGet(options *RequestGetOptions) (res RequestCustomeResponse, err error) {
	if options.URL == "" {
		return res, errors.New("必须提供url")
	}

	// 设置默认的params和headers
	defaultParams := map[string]string{}
	defaultHeaders := map[string]string{"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"}

	// 使用默认值或提供的值
	params := defaultParams
	if options.Params != nil {
		params = options.Params
	}

	headers := defaultHeaders
	if options.Headers != nil {
		headers = options.Headers
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", options.URL, nil)
	if err != nil {
		return res, err
	}

	// Add additional headers if provided
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	if params != nil {
		// Add query parameters if provided
		q := req.URL.Query()
		for key, value := range params {
			q.Add(key, value)
		}
		req.URL.RawQuery = q.Encode()
	}

	resp, err := client.Do(req)
	if err != nil {
		res.Msg = err.Error()
		return res, nil
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = resp.StatusCode
	if err := json.Unmarshal(body, &res.Content); err != nil {
		res.Content = string(body)
	}

	return res, nil
}

// RequestPost 函数用于发送POST请求
func RequestPost(options *RequestPostOptions) (res RequestCustomeResponse, err error) {
	if options.URL == "" {
		return res, errors.New("必须提供url")
	}

	// 设置默认的headers
	defaultHeaders := map[string]string{"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"}

	// 使用默认值或提供的值
	headers := defaultHeaders
	if options.Headers != nil {
		headers = options.Headers
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", options.URL, nil)
	if err != nil {
		return res, err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 如果提供了数据，则将其添加到请求体中
	if options.Data != nil {
		dataBytes, err := json.Marshal(options.Data)
		if err != nil {
			return res, err
		}
		req.Body = io.NopCloser(bytes.NewBuffer(dataBytes))
		req.Header.Set("Content-Type", "application/json")
	}

	resp, err := client.Do(req)
	if err != nil {
		res.Msg = err.Error()
		return res, nil
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = resp.StatusCode
	if err := json.Unmarshal(body, &res.Content); err != nil {
		res.Content = string(body)
	}

	return res, nil
}

//func main() {
//	res, _ := gops.RequestPost(&gops.RequestPostOptions{
//		URL: "http://127.0.0.1:8000/user/login",
//		Data: map[string]any{
//			"username": "ops",
//			"password":  123456,
//		},
//	})
//	fmt.Println(res)
//}
